package com.example.xfengshopping;

import android.content.Intent;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import home.fragment.HomeFragment;
import shoppingcart.fragment.ShoppingcartFragment;
import type.fragment.TypeFragment;
import type.fragment.TypeFragment.OnBackToHomeListener;
import user.fragment.UserFragment;

public class MainActivity extends AppCompatActivity implements OnBackToHomeListener {

    private TabLayout tabLayout;
    private ArrayList<Fragment> fragments;
    private static final String SHOW_CART_EXTRA = "show_cart_fragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化控件和Fragment
        tabLayout = findViewById(R.id.tabLayout);
        initFragment();
        setupTabListener();
        initInsets();

        // 检查是否需要直接显示购物车
        handleIntentExtras();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntentExtras();
    }

    private void handleIntentExtras() {
        boolean showCart = getIntent().getBooleanExtra(SHOW_CART_EXTRA, false);
        if (showCart) {
            loadFragment(2);
            tabLayout.selectTab(tabLayout.getTabAt(2));
            // 清除标志，避免再次显示购物车
            getIntent().removeExtra(SHOW_CART_EXTRA);
        } else {
            // 默认显示首页
            loadFragment(0);
            tabLayout.selectTab(tabLayout.getTabAt(0));
        }
    }

    private void initInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    private void initFragment() {
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());       // 首页（位置0）
        fragments.add(new TypeFragment());       // 分类（位置1）
        fragments.add(new ShoppingcartFragment()); // 购物车（位置2）
        fragments.add(new UserFragment());       // 我的（位置3）
    }

    private void setupTabListener() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                loadFragment(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    private void loadFragment(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.frameLayout, fragments.get(position));
        transaction.commit();
    }

    public void navigateToTypeFragment() {
        loadFragment(1);
        tabLayout.selectTab(tabLayout.getTabAt(1));
    }


    // 实现返回首页回调
    @Override
    public void onBackToHome() {
        loadFragment(0);
        tabLayout.selectTab(tabLayout.getTabAt(0));
    }

    // TypeFragment需调用的回调接口
    public interface OnBackToHomeListener {
        void onBackToHome();
    }

}
